﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Configuration;
using System.Data.SQLite;
using System.IO;

namespace HomeDMSObjectModel
{
    public class DBHelper
    {
        private ISessionFactory _factory;
        private string _filePath;

        private void CreateFactory()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
            cfg.AddAssembly(this.GetType().Assembly);
            cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, "Data Source=" + _filePath + @"\programm.db;Version=3");
            _factory = cfg.BuildSessionFactory();
        }

        public DBHelper(string filePath)
        {
            _filePath = filePath;
            FileInfo fi = new FileInfo(filePath + @"\programm.db");
            if (!fi.Exists)
            {
                Stream str = this.GetType().Assembly.GetManifestResourceStream("HomeDMSObjectModel.CreateScript.sql");
                RunCreateDBScript(fi.FullName,str);
            }
            CreateFactory();
        }

        public ISession OpenSession()
        {
            if (_factory == null)
            {
                CreateFactory();
            }
            return _factory.OpenSession();
        }

        private void RunCreateDBScript(string fileName,Stream scriptStream)
        {
            _filePath = fileName;
            SQLiteConnection con = new SQLiteConnection("Data Source=" + fileName + ";Version=3");
            con.Open();
            try
            {
                StreamReader sr = new StreamReader(scriptStream);
                string script = sr.ReadToEnd();
                sr.Close();
                SQLiteCommand cmd = new SQLiteCommand(con);
                cmd.CommandText = script;
                cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();     
            }
        }

        public void SaveDocument(Document doc)
        {
            ISession session = OpenSession();
            using (ITransaction trans = session.BeginTransaction())
            {
                try
                {
                    if (doc.DocumentId == int.MinValue)
                    {
                        session.Save(doc);
                    }
                    else
                    {
                        session.Update(doc);
                    }
                    trans.Commit();
                }
                catch(Exception ex)
                {
                    trans.Rollback();
                    throw new Exception(ex.Message, ex);
                }
                finally
                {
                    session.Close();
                }
            }
        }

        public Document GetDocument(int id)
        {
            ISession session = OpenSession();
            return session.Load<Document>(id);
        }
    }
}
